import userApi from '@/apis/user';
import type { UserApiType } from '@/apis/user/namespace';
import { CacheEnum } from '@/enum/cacheEnum';
import { RouterEnum } from '@/enum/routerEnum';
import customStorage from '@/hooks/useStorage';
import userStroe from '@/plugins/pinia/stores/user';
import router from '@/router';
import { ElMessage } from 'element-plus';
import menuServie from '@/hooks/useMenus';

export default () => {
  /**
   * 登出
   */
  function logout() {
    customStorage.remove(CacheEnum.TOKEN_NAME);
    customStorage.remove(CacheEnum.HISTORY_MENU);
    customStorage.remove(CacheEnum.REDIRECT_ROUTE_NAME);
    router.push({ name: RouterEnum.LOGIN });
    userStroe().clear();
  }

  /**
   * 登录
   * @param values
   */
  async function login(values: UserApiType.UserInterface) {
    const token = await userApi.login(values);
    const user = userStroe();
    user.clear();

    if (token) {
      // 存储token,设置过期时间为 3600000秒
      customStorage.setItem(CacheEnum.TOKEN_NAME, token, 3600000);
    } else {
      return;
    }

    // 获取并存储用户信息
    await user.getUserInfo();

    // 初始化菜单信息
    menuServie.init();

    // 用户状态为禁用
    if (!user.userInfo?.status) return;

    // 获取跳转登录前的页面;
    const routeName = customStorage.getItem(CacheEnum.REDIRECT_ROUTE_NAME);
    router.push({ name: routeName ?? RouterEnum.HOME });
  }

  /**
   * 注册
   * @param values
   */
  async function register(values: UserApiType.UserInterface) {
    const token = await userApi.register(values);
    if (token) {
      ElMessage.success('注册成功，请登录');
    }
  }

  return { logout, login, register };
};
